/**
 * HMI 只读选择表格数据管理 Composable
 *
 * 提供表格数据的获取、格式化、分页等功能
 * 使用统一的错误处理机制，确保用户体验一致性
 *
 * @param config 表格配置对象
 * @returns 数据管理相关的状态和方法
 */
import { ref, computed } from "vue";
import type { HmiOnlySelectRow, HmiOnlySelectConfig } from "../types";
import { useBaseTableData, DATA_STATUS } from "@/components/HmiCommon/composables/useBaseTableData";

// 复用基座的统一状态枚举
export { DATA_STATUS };

/**
 * 数据管理 Composable（基于 BaseTableData 抽象）
 */
export function useHmiOnlySelectData(config: HmiOnlySelectConfig) {
  const base = useBaseTableData<HmiOnlySelectRow>({
    apiPath: computed(() => config.apiPath),
    pageSize: computed(() => config.pagination?.pageSize || 10),
    group: computed(() => config.queryOptions?.group || []),
    orderByKey: computed(() => config.orderByKey),
    showSettingZone: computed(() => !!config.showSettingZone),
    displayZone: computed(() => config.displayZone),
    formatRow: (item, index) => ({ ...(item as any), _index: index }),
  });

  const selectedRows = ref<HmiOnlySelectRow[]>([]);
  const hasData = computed(() => base.tableData.value.length > 0);
  const currentPage = computed({
    get: () => Math.floor(base.pagination.offset / base.pagination.limit) + 1,
    set: (value) => {
      base.pagination.offset = (value - 1) * base.pagination.limit;
    },
  });

  function handleSelectionChange(selection: HmiOnlySelectRow[]) {
    selectedRows.value = selection;
  }

  return {
    // 状态
    tableData: base.tableData,
    loading: base.loading,
    total: base.total,
    selectedRows,
    pagination: base.pagination,
    data_status: base.dataStatus,
    DATA_STATUS,

    // 计算
    hasData,
    currentPage,

    // 方法
    fetchData: base.fetchData,
    refreshData: base.refreshData,
    resetData: () => {
      base.tableData.value = [] as any;
      base.total.value = 0;
      selectedRows.value = [];
      base.pagination.offset = 0;
      base.pagination.limit = config.pagination?.pageSize || 10;
    },
    handleSelectionChange,
    handlePaginationChange: base.handlePaginationChange,
  };
}
